<?php

namespace App\Services;

use App\Exceptions\InternalException;
use App\Exceptions\InvalidRequestException;
use App\Models\Application;
use App\Models\ApplicationProcesses;
use App\Models\ApplicationRecord;
use App\Models\Supplier;
use App\Models\Team;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class ApproveService
{
    public function get($model,$status){
        $sql = Application::with('project')->with('user')->where('model',$model)->when($status, function ($query, $status) {
            return $query->where(function($query) use ($status) {
                $query->where('status',$status);
            });
        });

        $sql->with($model);

        return $sql;
    }

    public function getSource($source,$model,$status){
        $source = explode(',',$source);
        $sql = Application::with('project')->with('user')->whereIn('source',$source)->when($status, function ($query, $status) {
            return $query->where(function($query) use ($status) {
                $query->where('status',$status);
            });
        });
        $sql->with($model);
        return $sql;
    }

    public function costs($model,$project_id){
        $sql = Application::with('project')->with('user')->where('model',$model)->where('project_id',$project_id)->where('status','approved');
        $sql = $sql->with($model)->get();
        return $sql;
    }

    public function records($id){
        $data = ApplicationRecord::with('role')->with('user')->where('application_id',$id)->get();
        return $data;
    }

    public function insert($input){
        $res = [];
        foreach ($input as $k => $v) {
            if($v){
                $res[$k] = $v;
            }
        }
        $res['status'] = 'pending';
        try {
            $data = Application::create($res);
            if($data){
                return $data;
            }
        } catch (\Throwable $th) {
            Log::info(json_encode($th));
            throw new InternalException('提交失败');
        }
    }

    public function review($input,$type){
        unset($input['id']);
        //查询状态
        $Application = Application::find($input['application_id']);
        if($Application->status == 'rejected'){
            throw new InvalidRequestException('该审批已被拒绝');
        }

        $level = 0;
        //只能一级一级审批
        $Record = ApplicationRecord::where('status','pending')->where('reviewer_id','<>',0)->where('application_id',$input['application_id'])->orderBy('level','asc')->first();
        if($Record->reviewer_id == $input['reviewer_id']){
            //判断是否轮到这个人
            $Record->comment = $input['comment'];
            $Record->status = $input['status'];
            $Record->save();
            $level = $Record->level;
        }else{
            throw new InvalidRequestException('暂无审批权限');
        }

        if($Application->type == 'apply'){
            $levelProcesses = ApplicationProcesses::where('level','<',6)->where('project_id',$Application->project_id)->orderBy('level','desc')->first();
        }else{
            $levelProcesses = ApplicationProcesses::where('project_id',$Application->project_id)->orderBy('level','desc')->first();
        }
        $reviewer_id = ApplicationRecord::where('status','pending')->where('application_id',$input['application_id'])->orderBy('level','asc')->first();
        if($reviewer_id){
            $Application->reviewer_id = $reviewer_id->reviewer_id;
        }

        $Application->invoice_numbers = $input['invoice_numbers'];
        $Application->invoice_file = $input['invoice_file'];
        $Application->receipt = $input['receipt'];
        $Application->invoice_type = $input['invoice_type'];
        $Application->pay_date = $input['pay_date'];
        if($input['status'] == 'approved'){
            $Application->is_process = 1;
        }


        //最后一级
        if($levelProcesses->level == $level || $input['status'] == 'rejected'){
            $Application->status = $input['status'];
            if($levelProcesses->level == $level && $input['status'] == 'approved' && $Application->model == 'WarehousesIn'){
                //如果是入库
                $WarehouseService = new WarehouseService();
                $WarehouseService->insApply($Application->source_id);
            }
            if($levelProcesses->level == $level && $input['status'] == 'approved' && $Application->model == 'WarehousesOut'){
                //如果是出库
                $WarehouseService = new WarehouseService();
                $WarehouseService->outsApply($Application->source_id);
            }

            //类型如果是删除
            if($Application->type == 'delete' && $input['status'] == 'approved'){
                if($Application->model == 'Supplier'){
                    Supplier::where('id',$Application->source_id)->delete();
                }

                if($Application->model == 'Team'){
                    Team::where('id',$Application->source_id)->delete();
                }
            }
        }
        $Application->save();
        return true;
    }

    public function revoke($source_id,$model,$project_id){
        //判断是否申请过
        $is = Application::where('source_id',$source_id)->where('model',$model)->where('user_id',Auth::user()->id)->where('project_id',$project_id)->orderBy('id','desc')->first();
        if(empty(($is))){
            throw new InvalidRequestException('未发起审批');
        }

        if($is->status == 'approved'){
            throw new InvalidRequestException('已经通过，无法撤销');
        }

        if($is->status == 'rejected'){
            // throw new InvalidRequestException('已经驳回，无法撤销');//
            $ApplicationRecord = ApplicationRecord::where('application_id',$is->id)->where('status','rejected')->first();
            //把驳回改成待审批
            $is->status = 'pending';
            $is->is_process = 0;
            $ApplicationRecord->status = 'pending';

            try {
                $data = DB::transaction(function () use ($is,$ApplicationRecord) {
                    $is->save();
                    $ApplicationRecord->save();
                    return true;
                });
                return $data;
            } catch (\Throwable $th) {
                Log::info(json_encode($th));
                throw new InternalException('提交失败');
            }
        }

        $ApplicationRecord = ApplicationRecord::where('application_id',$is->id)->where('status','<>','pending')->first();
        // if(!empty(($ApplicationRecord))){
        //     throw new InvalidRequestException('审批中无法撤回');
        // }
        try {
            $data = DB::transaction(function () use ($is) {
                $is->delete();
                ApplicationRecord::where('application_id',$is->id)->delete();
                return true;
            });
            return $data;
        } catch (\Throwable $th) {
            Log::info(json_encode($th));
            throw new InternalException('提交失败');
        }
    }
}